package com.fmatos.amazingwallpapers.imagemanagement;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.inject.Inject;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;

import com.fmatos.amazingwallpapers.image.database.ImagesDataSource;
import com.fmatos.amazingwallpapers.image.database.orm.DatabaseHelper;
import com.fmatos.amazingwallpapers.image.database.orm.DatabaseManager;
import com.fmatos.amazingwallpapers.image.database.orm.Photo;
import com.fmatos.amazingwallpapers.image.database.orm.repository.PhotoRepo;
import com.j256.ormlite.android.apptools.OpenHelperManager;

/**
 * Gets cached images (doesn't perform any download work)
 * @author fdematos
 *
 */

public class BitmapsRetrieverManager {

	private static final String TAG = BitmapsRetrieverManager.class.getSimpleName();
	private ConcurrentLinkedQueue<Photo> imageQueue;
	
	private FileManager filemanager;
	private PhotoRepo photoRepo;
	
	@Inject
	public BitmapsRetrieverManager(FileManager filemanager, PhotoRepo photoRepo) {
		this.filemanager = filemanager;
		this.photoRepo = photoRepo;
		
			imageQueue = new ConcurrentLinkedQueue<Photo>();
	}


	public BitmapsRetrieverManager(Context context) {
		
		DatabaseHelper databaseHelper =  DatabaseManager.getDatabaseHelper(); //OpenHelperManager.getHelper(context, DatabaseHelper.class);
		photoRepo = new PhotoRepo(databaseHelper);
		
		filemanager  = new FileManager(context);
		
		imageQueue = new ConcurrentLinkedQueue<Photo>();
		
	}


	/**
	 * Gets next image from DB according to album parameters.
	 * This method may be called from the main thread, and so should return in a short time.
	 * If there's heavy work to do it must be done in the background.
	 * @return
	 */
	public ImageView getNextImage() {

//		java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase:
		if ( imageQueue.isEmpty() ) {
			List<Photo> queue = photoRepo.getPhotos(); //datasource.getAllImages();
			Collections.shuffle(queue);
			imageQueue.addAll(queue);
		}
		
		// TODO retry get next image when filename is null, or file doesn't exist 
		// TODO resize image as needed
		Photo image = getNextImageFromQueue(imageQueue);

		ImageView view = null;
		if ( image != null ) {
			Bitmap bitmap = null;
			try {
				bitmap = filemanager.loadImageFromPath(image.getFilePath());
			} catch (FileNotAvailableException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO these kinds of checks should be made somewhere else
			if ( bitmap == null && ! filemanager.isFileExist(image.getFilePath())) {
				image.setFilePath(null);
				//datasource.updateFilename(image);
				photoRepo.update(image);
				Log.i(TAG,"Deleting missing file " + image.getCaption());
			} else {
				view = new ImageView();
				view.bitmap = bitmap;
				view.caption = image.getCaption();
			}
		}

		return view;
	}

	/**
	 * Returns the next bitmap to be displayed, 
	 * or null if no image at all can be found.
	 * @param imageQueue2
	 * @return
	 */
	private Photo getNextImageFromQueue(
			ConcurrentLinkedQueue<Photo> imageQueue2) {
		
		
		Photo image = null;
		
		while ( ! imageQueue2.isEmpty() ) {
			image = imageQueue2.poll();
			if ( !image.isCorrupt() && !image.isGif() && filemanager.isFileExist(image.getFilePath()) ) {
				break;
			}
//			Log.i(TAG,"Found row without file at #" + image.getId() + " caption = " + image.getCaption() );
		}
		
		
		return image;
	}

	public class ImageView {
		public Bitmap bitmap;
		public String caption;
	}

	//	
	//	public Bitmap getImage() {
	//
	//		if ( queuedImages == null ) {
	//			queuedImages = new ConcurrentLinkedQueue<ImageRow>();
	//		}
	//		
	//		if ( queuedImages.size() == 0 
	//				&& allImages != null && allImages.size() > 0 ) {
	//			queuedImages.addAll(allImages);
	//		}
	//		
	//		if ( queuedImages != null && queuedImages.size() > 0 ) {
	//			
	//			while ( ! queuedImages.isEmpty() ) {
	//				ImageRow image = queuedImages.poll();
	//				Bitmap bitmap = null;
	//				
	//				if ( bitmap  != null ) {
	//					return bitmap;
	//				}
	//			}
	//		}
	//		
	//		return null;
	//	}

}
